package com.shuhe.handler;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.util.TypeUtils;
import com.shuhe.common.EncryptUtils;
import com.shuhe.common.HttpClient;
import com.shuhe.domain.mock.*;
import com.shuhe.metastore.DBSql;
import com.shuhe.metastore.MetaMysql;
import com.shuhe.metastore.Neo4jDB;
import org.apache.log4j.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Enumeration;

import static com.shuhe.common.CommonFunction.*;


public class AiHandler extends HttpServlet {

    private static Logger logger = Logger.getLogger(AiHandler.class);

    @Override
    protected void doOptions(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp = setResponse(resp);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("AiHandler doGet");
    }


    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Connection conn = null;
        try {
            resp = setResponse(resp);
            resp.setCharacterEncoding("utf-8");
            resp.setContentType("application/json");

            String bodyStr = readAsChars(req);
            JSONObject bodyJson = JSONObject.parseObject(bodyStr);
            String sql = bodyJson.getString("sql");
            conn = DBSql.connect();
            ResultSet rs = DBSql.querySql(conn, sql);
            ArrayList<Object> columns = new ArrayList<>();
            ArrayList<Object> datas = getResultSet(rs);
            for (int i = 0; i < rs.getMetaData().getColumnCount(); i++) {
                String columnLabel = rs.getMetaData().getColumnLabel(i + 1);
                String columnType = rs.getMetaData().getColumnTypeName(i + 1).toLowerCase();
                JSONObject tmpJson = new JSONObject();
                tmpJson.put("columnLabel", columnLabel);
                tmpJson.put("columnType", columnType);
                columns.add(tmpJson);
            }
            JSONObject resultJson = getResultJson("200", "success");
            resultJson.put("columns", columns);
            resultJson.put("datas", datas);
            resp.getWriter().write(resultJson.toJSONString());

        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            closeDb(conn);

        }
    }


}
